﻿using System;
using InterfaceLiftLib.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Linq;

namespace InterfaceLiftLib.Converters.Json
{
    public class ResolutionConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {

            try
            {
                //is an array?
                var resolutions = JArray.Load(reader)
                                  .Values()
                                  .Select(item => ResolutionFromString(item.Value<string>()))
                                  .ToList();

                return resolutions;
            }
            catch 
            {
                try
                {
                    //is a single item?
                    var val = reader.Value as string;
                    return ResolutionFromString(val);
                }
                catch
                {
                    return null;   
                }
            }
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof (string);
        }

        private static Resolution ResolutionFromString(string s)
        {
            var values = s.Split('x');
            return new Resolution(UInt32.Parse(values[0]), UInt32.Parse(values[1]));
        }
    }
}
